/**
 * @author: ppkpub (ppkpub.org),  baibingyi(baiby@live.cn)
 * 2016-11-05 TechCrunch
 */ 

var app = require('./express')();
var http = require('http').Server(app);
var io = require('./socket.io')(http);
var fs = require('fs');
var crypto = require('crypto');

// TODO 此处模拟本地资源文件目录, 实际场景应是解析出的资源地址

var BASE_PATH = '/home/yyz/';

app.get('/', function(req, res){
    var reqQuery = req.query;
    // 获取资源标识
    var ppkUri = reqQuery['ppk-uri'];

    console.log(ppkUri);
    console.log();

    // 实际应用场景下无需做以下处理,直接访问请求资源位置即可. 此处只是模拟场景
    var lastIndex = ppkUri.lastIndexOf('/');
    ppkUri = ppkUri.substring(lastIndex+1, ppkUri.length);

    console.log(ppkUri);
    console.log();

    var fileContent_str = fs.readFileSync(BASE_PATH + ppkUri,'utf-8');

    console.log('str: '+ (fileContent_str))

    console.log();

    var fileContent_arr = fileContent_str.split(' ');
    var fileTime = fileContent_arr[0];

    console.log(fileContent_str);
    console.log('time: '+fileTime);

    // 组件资源标识相关sign
    var resSign = {
        'ppk-uri':ppkUri+fileTime+'.0#',
        'algo':'MD5withRSA',
        'debug_pubkey':'54032efa9769c2e93797cd06',
        'sign_base64':'sign_base64'
    };

    var sign = JSON.stringify(resSign);
    res.setHeader('Set-Cookie', ['ppk-sign='+ sign]);
    res.send(fileContent_arr[1]);
});


// 监听socket 此处在本次演示中并没有提醒相关作用,只是实例通信
io.on('connection', function(socket){
    var query = socket.request._query; //获取请求参数
    var uuid = query.uuid; // 唯一标识
    console.log(uuid + '  connected');
    //监听用户退出
    socket.on('disconnect', function(){
        console.log('disconnect');
    });

});

// 监听3000端口的socket链接
http.listen(3000, function(req,rep){
    console.log('listening on *:3000');
});